﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Repository;
using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Cxuu.Service
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ArticleService
    {
        private readonly ArticleRepository articleDal;
        private readonly ArticleContentRepository articleContentDal;
        private readonly ICacheManager cacheManager;
        private readonly string cacheKey;
        private readonly string cacheListKey;
        public ArticleService(ArticleRepository articleRepository, ArticleContentRepository contentRepository, ICacheManager CacheManager)
        {
            cacheManager = CacheManager;
            articleDal = articleRepository;
            articleContentDal = contentRepository;
            cacheKey = cacheManager.CacheName() + "Content_Info_";
            cacheListKey = cacheManager.CacheName() + "Content_List_";
        }

        /// <summary>
        /// 前台查询一条
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ViewArticleAndContent> GetAsync(int? id)
        {
            ViewArticleAndContent article = cacheManager.Get<ViewArticleAndContent>(cacheKey + id);
            if (article == null)
            {
                article = await articleDal.GetAsync(id);
                cacheManager.Set(cacheKey + id, article, TimeSpan.FromHours(10));//缓存2秒
            }
            await articleDal.IncHits(id);//浏览+1
            return article;
        }

        /// <summary>
        /// 后台编辑一条信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<EditArticleAndContent> GetEditAsync(int? id)
        {
            return await articleDal.GetEditAsync(id);
        }

        /// <summary>
        /// 按CID获取全部列表 后台
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<Page<ViewArticleAndCate>> GetListByCidAdminAsync(int? cid, int page, int limit, int uid, string keyWord, int status)
        {
            return await articleDal.GetListAsync(cid, page, limit, "article.Id desc", keyWord, status, uid);
        }

        /// <summary>
        /// 获取全部列表  前台 所有列表 博客首页  获取 status=1 列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<Page<ViewArticleAndCate>> GetListAsync(int page, int limit)
        {
            return await articleDal.GetListAsync(0, page, limit, "article.Id desc", "", 1);
        }

        /// <summary>
        /// 按CID获取全部列表 获取 status=1 列表  前台
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<Page<ViewArticleAndCate>> GetListByCidAsync(int cid, int page, int limit)
        {
            return await articleDal.GetListAsync(cid, page, limit, "article.Id desc", "", 1);
        }

        /// <summary>
        /// 搜索列表 前台
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<Page<ViewArticleAndCate>> ArticleSearchPageList(int page, int limit, string keyword)
        {
            return await articleDal.GetListAsync(page, limit, keyword);

        }

        /// <summary>
        /// 按CID获取指定条数列表 前台
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="limit"></param>
        /// <param name="cacheName"></param>
        /// <param name="cacheTime"></param>
        /// <param name="att"></param>
        /// <param name="img"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        public async Task<List<ViewArticleAndCate>> CxuuList(string cid, int limit, string cacheName, int cacheTime = 600, int att = 0, bool img = false, string orderby = "Id desc")
        {
            List<ViewArticleAndCate> article = cacheManager.Get<List<ViewArticleAndCate>>(cacheListKey + cacheName);
            if (article == null)
            {
                article = await articleDal.GetListByLimtAsync(cid, limit, img, att, "article." + orderby);
                if (cacheName != null)
                    cacheManager.Set(cacheListKey + cacheName, article, TimeSpan.FromSeconds(cacheTime));//缓存
            }
            return article;
        }


        /// <summary>
        /// TAG 获取指定条数列表 前台
        /// </summary>
        /// cxuuList("table='article' cid='1,2,3' limit='11' cachetime='600' cachename='cate_11' img='false' att='0' order='id'  orderby='desc'")
        public async Task<List<ViewArticleAndCate>> CxuuListTag(string str)
        {

            List<ListTag> cxuuTag = new();
            MatchCollection result = Regex.Matches(str, @"([a-z0-9_]*)='(.*?)'\s*");
            for (int i = 0; i < result.Count; i++)
            {
                cxuuTag.Add(new() { Key = result[i].Groups[1].Value, Value = result[i].Groups[2].Value });
            }

            string cid = cxuuTag.FirstOrDefault(s => s.Key == "cid").Value ??= "0";
            int limit = Convert.ToInt32(cxuuTag.FirstOrDefault(s => s.Key == "limit").Value ??= "11");
            string cacheName = cxuuTag.FirstOrDefault(s => s.Key == "cachename").Value;
            int cacheTime = Convert.ToInt32(cxuuTag.FirstOrDefault(s => s.Key == "cachetime").Value);
            int att = Convert.ToInt32(cxuuTag.FirstOrDefault(s => s.Key == "att").Value ??= "0");
            bool img = Convert.ToBoolean(cxuuTag.FirstOrDefault(s => s.Key == "img").Value ??= "false");
            string order = cxuuTag.FirstOrDefault(s => s.Key == "order").Value ??= "id";
            string orderby = cxuuTag.FirstOrDefault(s => s.Key == "orderby").Value ??= " desc";

            List<ViewArticleAndCate> article = cacheManager.Get<List<ViewArticleAndCate>>(cacheListKey + cacheName);
            if (article == null)
            {
                article = await articleDal.GetListByLimtAsync(cid, limit, img, att, "article." + order + " " + orderby);
                if (cacheName != null)
                    cacheManager.Set(cacheListKey + cacheName, article, TimeSpan.FromSeconds(cacheTime));//缓存

            }
            return article;
        }



        public virtual async Task<Article> InsertArticleAndContentAsync(Article article, ArticleContent content)
        {
            Article articleRes = await articleDal.InsertArticleAndContentAsync(article, content);
            cacheManager.RemoveCacheAsync(cacheListKey + articleRes.Cid);
            return articleRes;
        }

        public virtual async Task<int> UpdateArticleAndContentAsync(Article article, ArticleContent content)
        {
            cacheManager.RemoveCacheAsync(cacheKey + article.Id);
            return await articleDal.UpdateArticleAndContentAsync(article, content);
        }

        public virtual async Task<int> UpdateArticleAttAsync(int id, int status, string att)
        {
            return await articleDal.UpdateArticleAttAsync(id, status, att);
        }


        /// <summary>
        /// 删除一条信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<int> DelArticleAndContentAsync(int id)
        {
            if (await articleDal.DeleteByPriKeyAsync(id) > 0)
            {
                await articleContentDal.DeleteByPriKeyAsync(id);
                cacheManager.RemoveCacheAsync(cacheKey + id);
                return 1;
            }
            return 0;
        }
    }
}
